package com.tingyu.blog.service;

import com.tingyu.blog.dao.CommentRepository;
import com.tingyu.blog.po.Comment;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    private CommentRepository commentRepository;

    /**
     * 根据博客id获取评论列表
     * @param blogId
     * @return
     */
    @Override
    public List<Comment> listCommentByBlogId(int blogId) {
        Sort sort = Sort.by(Sort.Direction.DESC,"createTime");
        List<Comment> comments = commentRepository.findByBlogIdAndParentCommentNull(blogId,sort);
        return eachTopComment(comments);
    }


    //获取顶级评论集合
    private List<Comment> eachTopComment(List<Comment> comments){
        List<Comment> topList = new ArrayList<>();
        for (Comment comment:comments) {
            Comment c = new Comment();
            BeanUtils.copyProperties(comment,c);
            topList.add(c);
        }
        combineChild(topList);
        return topList;
    }


    //循环设置某顶级元素与合为合并后的子代集合的关系
    private void combineChild(List<Comment> comments){
        for (Comment comment:comments) {    //循环顶级元素
            List<Comment> replys = comment.getReplyComments();   //获取第二代
            for (Comment reply:replys) {    //遍历第二代
                recursive(reply);   //递归二代以后
            }
            //设置某顶级元素的回复集合为合并后的子代集合
            comment.setReplyComments(tempList);
            tempList = new ArrayList<>();   //清空
        }
    }


    private List<Comment> tempList = new ArrayList<>();     //暂存集合
    //递归函数，合并二代及以下代，到暂存集合
    private void recursive(Comment comment){
        tempList.add(comment);  //二代，添加到暂存集合
        if (comment.getReplyComments().size()>0){   //二代是有三代
            List<Comment> replys = comment.getReplyComments();
            for (Comment r: replys){    //遍历三代
                tempList.add(r);    //三代，添加到暂存集合
                if (r.getReplyComments().size()>0){
                    recursive(r);   //递归继续遍历添加
                }
            }
        }
    }



    /**
     * 保存提交的评论
     * @param comment
     * @return 返回提交的评论
     */
    @Transactional
    @Override
    public Comment saveComment(Comment comment) {
        int parentCommentId = comment.getParentComment().getId();   //获取页面传过来的父级评论id（-1）
        if (parentCommentId != -1){
            comment.setParentComment(commentRepository.getOne(parentCommentId));
        }else {
            comment.setParentComment(null);     //没有父评论
        }
        comment.setCreateTime(new Date());   //初始化创建时间
        return commentRepository.save(comment);     //保存评论到数据库
    }
}
